package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional //事务
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult upload(MultipartFile multipartFile) {

        //todo 1.校验参数
        if(null == multipartFile){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //todo 2.上传到minio
        //todo 2.1 保证上传的图片名字唯一  xxxx.jpg   xxx.png
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String newName = fileName + suffix;
        String path = null;
        try {
            path = fileStorageService.uploadImgFile("", newName, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //todo 3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        //todo 3.1 补全参数即可
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(path);
        wmMaterial.setIsCollection((short)0);//默认不收藏
        wmMaterial.setUserId(user.getId());
        wmMaterialMapper.insert(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //todo 1.校验参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //todo 1.1 校验分页参数
        dto.checkParam();

        //todo 1.2 校验是否登录
        WmUser user = WmThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //todo 2.根据条件查询数据即可
        //todo 2.1 根据分页条件查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //todo 2.2 根据是否收藏查询
        if(dto.getIsCollection() != null && dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //todo 2.3 只能查询自己的素材
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //todo 2.4 根据时间排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = wmMaterialMapper.selectPage(page, wrapper);

        //todo 3.封装返回值（难点）
        //todo 1. 封装一个PageResponseResult 对象  多态（子类对象指向父类引用）
        ResponseResult responseResult = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        responseResult.setCode(200);
        responseResult.setErrorMessage("查询成功过");
        return responseResult;
    }
}
